import uuid

from django.db import models
from comment.log_code import LogCodes


# Create your models here.

class User(models.Model):
    uid = models.CharField(max_length=120, default=str(uuid.uuid4()).replace("-",""), verbose_name="uid")
    name = models.CharField(max_length=128, verbose_name="名称")
    phone = models.CharField(max_length=20, verbose_name="联系电话")
    email = models.CharField(max_length=64, verbose_name="邮箱")
    is_admin = models.BooleanField(default=False, verbose_name="管理员权限")
    main_password = models.CharField(max_length=128, validators="密码")
    
    @staticmethod
    def find_by_id(id):
        user = User.objects.get(id=id)
        if type(user).__name__ == "User":
            return user
        else:
            return None
    
    @staticmethod
    def find_by_name(name):
        if name == None:
            return None
        user = User.objects.get(name=name)
        if user:
            return user
        else:
            return None
    
    @staticmethod
    def is_admin_by_id(id):
        user = User.find_by_id(id)
        if user:
            return user.is_admin
        return False
    
    @staticmethod
    def get_username_by_id(id):
        user = User.find_by_id(id)
        if user:
            return [user.name]
        else:
            return [None, LogCodes.SELECT_ERROR]
    
    @staticmethod
    def get_password_by_name(name):
        user = User.find_by_name(name)
        if user == None:
            return None
        else:
            return user.main_password
    
    @staticmethod
    def get_id_by_name(name):
        user = User.find_by_name(name)
        if user == None:
            return None
        else:
            return user.id
    
    @staticmethod
    def create_user(name, password, email, phone):
        try:
            user = User.objects.get(name=name)
        except Exception as e:
            user = None
        if not user is None:
            return None
        else:
            return User.objects.create(name=name, main_password=password, email=email, phone=phone)
    
    def loads(self, ):
        pass
    
    def dumps(self):
        pass
    
    def load(self):
        pass
    
    def dump(self):
        pass
    
    class Meta:
        db_table = 'tb_user'
        verbose_name = '用户'
        verbose_name_plural = verbose_name
    
    def __str__(self):
        return """{"id":{},"name":"{}","phone":"{}","email":"{}"}""".format(self.id, self.name, self.phone, self.email)
